/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.free.ts.contact.web;

import be.free.ts.support.web.AsyncBasicPresenter;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.user.client.ui.HasValue;
import com.google.inject.Inject;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;

import javax.inject.Provider;
import java.util.Date;

/**
 * @author Christophe De Blende
 * @since 05/01/13
 */
public class CreateContactPresenter extends AsyncBasicPresenter<CreateContactPresenter.Display> {

	public interface Display extends WidgetDisplay {

		HasClickHandlers createContactButton();

		HasValue<String> firstName();

		HasValue<String> lastName();

		HasValue<String> ssin();

		HasValue<Date> birthDate();
	}

	private final Provider<ContactRequest> contactRequestProvider;

	private final ContactPresenter contactPresenter;

	@Inject
	public CreateContactPresenter(AsyncProvider<Display> display, EventBus eventBus, Provider<ContactRequest> contactRequestProvider,
								  ContactPresenter contactPresenter) {
		super(display, eventBus);
		this.contactRequestProvider = contactRequestProvider;
		this.contactPresenter = contactPresenter;
	}

	@Override
	protected void onBind() {
		if (!contactPresenter.isBound()) {
			contactPresenter.bind();
			contactPresenter.revealDisplay();
		}

		display.createContactButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				GWT.log("Create contact event.");

				ContactRequest contactRequest = contactRequestProvider.get();
				ContactProxy contact = contactRequest.create(ContactProxy.class);
				contact.setBirthDate(display.birthDate().getValue());
				contact.setFirstName(display.firstName().getValue());
				contact.setLastName(display.lastName().getValue());
				contact.setSsin(display.ssin().getValue());
				contactRequest.save(contact).fire();
			}
		});
	}

	@Override
	protected void onUnbind() {
	}

	@Override
	protected void onRevealDisplay() {

		contactPresenter.getDisplay().getContent().clear();
		contactPresenter.getDisplay().getContent().add(getDisplay().asWidget());
	}

}
